class Paginator {
    constructor(root, onPageChangeCallback, options = {}) {
        this.root = root;

        // 【页码变化的回调函数】
        this.onPageChangeCallback = onPageChangeCallback;

        this.options = {
            totalPages: options.totalPages || 100,
            currentPage: options.currentPage || 1,
        };

        // 绘制基本元素
        this.renderBasic();

        // 绘制页码
        this.renderPagers();

        // 找出控件元素
        this.findElements();

        // 绑定事件
        this.bindEvents();
    }

    /* 绑定事件 */
    bindEvents() {
        const pgThis = this;

        /* 点击页码监听 */
        for (let i = 0; i < this.pagers.length; i++) {
            const pager = this.pagers[i];

            pager.addEventListener("click", () => {
                pgThis.setCurrentPager(pager);
                // console.log("turn to page", pager.innerText)

                // 不能这么写！分页器就跟mt耦合了
                // mt.turnToPage(pgThis.options.currentPage)

                // 调用用户传入的【页码变化的回调函数】
                // if(pgThis.onPageChangeCallback){
                //     pgThis.onPageChangeCallback()
                // }
                pgThis.onPageChangeCallback &&
                    pgThis.onPageChangeCallback(pgThis.options.currentPage);
            });
        }

        // 首页按钮监听
        pgThis.btnFirst.onclick = function (e) {
            pgThis.setCurrentPager(pgThis.pagers[0]);
            pgThis.onPageChangeCallback &&
                pgThis.onPageChangeCallback(pgThis.options.currentPage);
        };
        // 末页按钮监听
        pgThis.btnLast.onclick = function (e) {
            pgThis.setCurrentPager(pgThis.pagers[pgThis.pagers.length - 1]);
            pgThis.onPageChangeCallback &&
                pgThis.onPageChangeCallback(pgThis.options.currentPage);
        };
        // 上页按钮监听
        pgThis.btnPrev.onclick = function (e) {
            if (pgThis.options.currentPage != 1) {
                pgThis.setCurrentPageNum(pgThis.options.currentPage - 1);
                pgThis.onPageChangeCallback &&
                    pgThis.onPageChangeCallback(pgThis.options.currentPage);
            }
        };
        // 下页按钮监听
        // TODO
        pgThis.btnNext.onclick = function (e) {
            if (pgThis.options.currentPage != pgThis.options.totalPages) {
                pgThis.setCurrentPageNum(pgThis.options.currentPage + 1);
                pgThis.onPageChangeCallback &&
                    pgThis.onPageChangeCallback(pgThis.options.currentPage);
            }
        };

        // 跳转按钮监听
        pgThis.btnGo.onclick = function (e) {
            const pn = pgThis.ipPagenum.value * 1;
            pgThis.setCurrentPageNum(pn);
            pgThis.onPageChangeCallback &&
                pgThis.onPageChangeCallback(pgThis.options.currentPage);
        };
    }

    /* 设置当前页码 */
    setCurrentPageNum(n) {
        console.log("setCurrentPageNum", n);

        // 那个页码的innerText为n 则将其高亮
        for (let i = 0; i < this.pagers.length; i++) {
            const pager = this.pagers[i];
            if (pager.innerText == n) {
                this.setCurrentPager(pager);
                console.log("retruned", pager);
                return;
            }
        }

        // 走到这说明当前页码中没有n
        this.options.currentPage = n;
        // 重绘页码
        this.renderPagers();
    }

    /* 设置当前页码：当前页码高亮 其余取消高亮 */
    setCurrentPager(pagerElement) {
        // 记录当前页为pagerElement中的文本
        this.options.currentPage = pagerElement.innerText * 1;
        this.ipPagenum.value = this.options.currentPage;

        // 所有页码取消高亮
        for (let i = 0; i < this.pagers.length; i++) {
            const pager = this.pagers[i];
            pager.style.backgroundColor = "white";
        }

        // 当前页码设置高亮
        pagerElement.style.backgroundColor = "orange";
    }

    /* 绘制页码 */
    renderPagers() {
        /* 
            _renderPagers(
                [
                    [1,2],
                    [],
                    [18,22],
                    [],
                    [123,124]
                ]
            )
        */
        const _renderPagers = (ranges) => {
            ranges.forEach(
                // 遍历每一组范围
                (r) => {
                    if (r.length != 0) {
                        for (let i = r[0]; i <= r[1]; i++) {
                            if (i === this.options.currentPage) {
                                this.pagerBox.innerHTML += `<p style="background-color:orange;border: 1px solid rgb(51, 51, 51); margin: 0px 5px; padding: 0px 5px;">${i}</p>`;
                            } else {
                                this.pagerBox.innerHTML += `<p style="border: 1px solid rgb(51, 51, 51); margin: 0px 5px; padding: 0px 5px;">${i}</p>`;
                            }
                        }
                    } else {
                        this.pagerBox.innerHTML += "...";
                    }
                }
            );
        };

        this.pagerBox.innerHTML = "";
        if (this.currentPageOnEdge()) {
            _renderPagers([
                // 绘制头5页
                [1, 5],

                // 绘制...
                [],

                // 绘制尾5页
                [this.options.totalPages - 4, this.options.totalPages],
            ]);
        } else {
            // 绘制头2页
            // 绘制...
            // 绘制中间5页
            // 绘制...
            // 绘制尾2页
            _renderPagers([
                [1, 2],
                [],
                [this.options.currentPage - 2, this.options.currentPage + 2],
                [],
                [this.options.totalPages - 1, this.options.totalPages],
            ]);
        }

        // 重新找页码
        this.pagers = this.root.querySelectorAll("p");
    }

    /* 判断当前页是否位于边缘地带[1,5] [中心地带] [120,124] */
    currentPageOnEdge() {
        console.log("currentPageOnEdge", this.options.currentPage);
        return (
            (this.options.currentPage >= 1 && this.options.currentPage <= 5) ||
            this.options.currentPage > this.options.totalPages - 5
        );
    }

    /* 找出控件元素 */
    findElements() {
        // 首页
        this.btnFirst = this.root.querySelector("#btnFirst");

        // 末页
        this.btnLast = this.root.querySelector("#btnLast");

        // 上一页
        this.btnPrev = this.root.querySelector("#btnPrev");

        // 下一页
        this.btnNext = this.root.querySelector("#btnNext");

        // 用户输入框
        this.ipPagenum = this.root.querySelector("input");

        // 跳转按钮
        this.btnGo = this.root.querySelector("button");
    }

    /* 绘制基本元素 */
    renderBasic() {
        this.root.innerHTML = ` 
        <div class="container"
            style="padding: 0px; width: 800px; height: 40px; border: 1px solid rgb(51, 51, 51); margin: 30px auto; display: flex; justify-content: center; align-items: center;">
            <div style="border: 1px solid rgb(51, 51, 51); padding: 0px 5px; margin: 0px 5px; background-color: rgb(255, 255, 255);"
                id="btnFirst" disabled="false">first</div>
            <div style="border: 1px solid rgb(51, 51, 51); padding: 0px 5px; margin: 0px 5px; background-color: rgb(255, 255, 255);"
                id="btnPrev" disabled="false">prev</div>

            <div style="display: flex; justify-content: center; align-items: center;" class="pagers">
            </div>

            <div style="border: 1px solid rgb(51, 51, 51); padding: 0px 5px; margin: 0px 5px; background-color: rgb(255, 255, 255);"
                id="btnNext" disabled="false">next</div>
            <div style="border: 1px solid rgb(51, 51, 51); padding: 0px 5px; margin: 0px 5px; background-color: rgb(255, 255, 255);"
                id="btnLast" disabled="false">last</div>
            <input type="number" style="outline: none; width: 50px; height: 20px;">
            <button style="outline: none; width: 30px; height: 24px; margin-left: 5px;">go</button>
        </div>                               
        `;
        // 页码容器
        this.pagerBox = this.root.querySelector(".pagers");
    }
}
